{% extends './base.html' %}
{% block title %}文章编辑{% endblock %}
{% block header %}
    <link href="{% static 'cms/plugins/jquery-tags-input/jquery.tagsinput.min.css' %}" rel="stylesheet">
    <style>
        span.label {
            cursor: pointer;
            margin-right: 6px;
        }
    </style>
{% endblock %}
{% block footer %}
    <script type="text/javascript" src="{% static 'cms/plugins/jquery-tags-input/jquery.tagsinput.min.js' %}"></script>
    <script>
        // 转form表单为{}
        function fromToJson(el) {
            var result = {}
            var formArr = el.serializeArray()
            for (let i = 0; i < formArr.length; i++) {
                if (formArr[i]['name'] !== 'tags') {
                    if (formArr[i]['value']) {
                        result[formArr[i]['name']] = formArr[i]['value']
                    } else {
                        return false
                    }
                } else {
                    result[formArr[i]['name']] = $('#tags').val()
                }
            }
            return result
        }

        // 上传封面
        $('.upload-btn').click(function () {
            var uploadBtn = $('<input type="file">')
            uploadBtn.change(function () {
                lightyear.loading('show')
                var file = this.files[0]
                var formData = new FormData()
                formData.append('file', file)
                $ajax.post({
                    url: '/cms/upload/',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        lightyear.loading('hide')
                        if (res.code === 200) {
                            $('input[name=thumbnail]').val(res.data.url)
                            lightyear.notify('上传成功~~', 'success', 1000)
                        } else {
                            lightyear.notify('上传失败~~', 'danger', 1000)
                        }
                    }
                })
            })
            uploadBtn.trigger('click')
        })
        // 提交
        // 模拟成功
        $('#form-edit').submit(function (e) {
            e.preventDefault()
            var result = fromToJson($(this))
            if (result) {
                $ajax.post({
                    url: location.pathname,
                    data: result,
                    success: function (res) {
                        lightyear.loading('hide');
                        if (res.code === 200) {
                            lightyear.notify(res.msg + '页面即将自动跳转~', 'success', 1000);
                            setTimeout(function () {
                                location.replace('/cms/posts/')
                            })
                        } else {
                            lightyear.notify(res.msg, 'danger', 1000);
                        }
                    }
                })
            } else {
                lightyear.notify('还有未填项~~', 'danger', 1000)
            }
        })
        // 模拟失败
        $('#fail-btn').click(function (e) {
            e.preventDefault()
            lightyear.loading('show');
            // 假设ajax提交操作
            setTimeout(function () {
                lightyear.loading('hide');
                lightyear.notify('服务器错误，请稍后再试~', 'danger', 1000);
            }, 2000)
        })
        // 标签
        $('#tags-box span.label').click(function () {
            var pk = $(this).attr('data-pk')
            var value = $(this).attr('data-value')
            if ($(this).attr('data-selected') == '0') { // 插入
                if (!$('#tags').tagExist(value)) {  //不存在
                    $('#tags').addTag(value)
                }
            } else { // 删除
                $('#tags').removeTag(value)
            }
        })
        $('.js-tags-input').each(function () {
            var $this = $(this);
            $this.tagsInput({
                height: $this.data('height') ? $this.data('height') : '38px',
                width: '100%',
                defaultText: $this.attr("placeholder"),
                removeWithBackspace: false,
                delimiter: [','],
                maxCount: 10,
                interactive: false, //是否允许添加标签，false为阻止
                placeholderColor: '#666666', //设置defaultText的颜色
                onAddTag: function (tag) {//增加标签的回调函数
                    var label = $('#tags-box span[data-value="' + tag + '"]')
                    label.attr('data-selected', '1')
                    label.removeClass('label-info').addClass('label-dark')
                },
                onRemoveTag: function (tag) { //删除标签的回调函数
                    var label = $('#tags-box span[data-value="' + tag + '"]')
                    label.attr('data-selected', '0')
                    label.removeClass('label-dark').addClass('label-info')
                },
                onChange: function (tag) { //改变一个标签时的回调函数*/
                },
            });
        });
        // 添加tags
        {% if post %}
            {% for tag in post.tags %}
                $('#tags').addTag('{{ tag.name }}')
            {% endfor %}
        {% endif %}

    </script>
{% endblock %}
{% block main %}
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-body">
                    <form action="#" method="post" class="row" id="form-edit">
                        <div class="form-group col-md-12">
                            <label for="title">标题</label>
                            <input type="text" class="form-control" id="title" name="title"
                                   placeholder="请输入标题" value="{{ post.title }}"/>
                        </div>

                        <div class="form-group col-md-12">
                            <label for="desc">描述</label>
                            <textarea class="form-control" id="desc" name="desc" rows="5"
                                      placeholder="描述">{{ post.content|safe }}</textarea>
                        </div>

                        <div class="form-group col-md-12">
                            <label for="category">分类</label>
                            <div class="form-controls">
                                <select name="category" class="form-control" id="category">
                                    <option value="">请选择分类</option>
                                    {% for category in categories %}
                                        {% if post and post.category.id == category.id %}
                                            <option value="{{ category.id }}" selected>{{ category.name }}</option>
                                        {% else %}
                                            <option value="{{ category.id }}">{{ category.name }}</option>
                                        {% endif %}
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="form-group col-md-12">
                            <label for="tags">标签</label>
                            <input class="js-tags-input form-control" type="text" id="tags" name="tags"
                                   value="">
                            <div class="form-controls" id="tags-box">
                                {% for tag in tags %}
                                    <span class="label label-info" data-pk="{{ tag.id }}"
                                          data-selected="0" data-value="{{ tag.name }}">{{ tag.name }}
                                    </span>
                                {% endfor %}
                            </div>
                        </div>

                        <div class="form-group col-md-12">
                            <label>封面图</label>
                            <div class="input-group">
                                <input type="text" class="form-control" name="thumbnail"
                                       placeholder="点击上传或者填写封面地址" value="{{ post.thumbnail }}">
                                <div class="input-group-btn">
                                    <button type="button" class="btn btn-default upload-btn">上传封面</button>
                                </div>
                            </div>
                        </div>


                        <div class="form-group col-md-12">
                            <label>内容</label>
                            <textarea class="form-control" name="content" rows="5"
                                      placeholder="内容">{{ post.content|safe }}</textarea>
                        </div>

                        <div class="form-group col-md-12">
                            <label>是否推荐</label>
                            <div class="clearfix">
                                {% if post.is_recom %}
                                    <label class="lyear-radio radio-inline radio-primary">
                                        <input type="radio" name="is_recom" value="1" checked><span>是</span>
                                    </label>
                                    <label class="lyear-radio radio-inline radio-primary">
                                        <input type="radio" name="is_recom" value="0"><span>否</span>
                                    </label>
                                {% else %}
                                    <label class="lyear-radio radio-inline radio-primary">
                                        <input type="radio" name="is_recom" value="1"><span>是</span>
                                    </label>
                                    <label class="lyear-radio radio-inline radio-primary">
                                        <input type="radio" name="is_recom" value="0" checked><span>否</span>
                                    </label>
                                {% endif %}
                            </div>
                        </div>
                        <div class="form-group col-md-12">
                            <button type="submit" class="btn btn-primary" id="ajax-btn">提交</button>
                            <button type="reset" class="btn btn-default">重置</button>
                        </div>
                    </form>

                </div>
            </div>
        </div>

    </div>
{% endblock %}

